import { noop } from 'lodash-es'
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue';
interface useSearchTableType {
    searchAPI: Function;
    queryFactory: Function;
    afterSearch?: typeof noop;
    beforeSearch?: typeof noop;
    immediate: boolean;
    pageConfig?: Function
}
export function useSearchTable({
    searchAPI,
    queryFactory,
    afterSearch = noop,
    beforeSearch = noop,
    immediate = true,
    pageConfig = noop
}: useSearchTableType
) {
    const query = ref(queryFactory())
    const loading = ref(false)
    const memoryQuery = ref(null)
    const dataList = ref([])
    const data = ref()
    const page = ref(pageConfig() || {
        pageNo: 1,
        pageSize: 10,
        total: 0
    })

    const reset = () => {
        page.value.pageNo = 1
        query.value = queryFactory()
        query.value.sortField && (query.value.sortField = '')
        query.value.sortType && (query.value.sortType = '')
        search()
    }

    const setMemoryQuery = () => {
        const { pageNo, pageSize } = page.value
        for (let valueKey in query.value) {
            if (query.value[valueKey] === "" || query.value[valueKey] === null || query.value[valueKey] === undefined) {
                delete query.value[valueKey]
            } else if (typeof query.value[valueKey] == 'string') {
                query.value[valueKey] = query.value[valueKey].trim()
            }
        }
        memoryQuery.value = { pageNo, pageSize, ...query.value }
    }

    const search = async (pages: any = 1) => {
        page.value.pageNo = pages
        page.value.total = 0
        await updateDatalist()
    }

    const updateDatalist = async () => {
        try {
            beforeSearch()
            loading.value = true
            setMemoryQuery()
            const res = await searchAPI(memoryQuery.value)
            dataList.value = res.result.records ? res.result.records : (res.result.detail ? res.result.detail.records : res.result)
            data.value = res.result
            page.value.total = res.result.detail ? res.result.detail.total : res.result.total
            afterSearch()
        } catch (e) {
            console.log("e", e)
            message.error(e)
        } finally {
            loading.value = false
        }
    }

    const onPageChange = () => {
        const { pageNo, pageSize } = page.value
        Object.assign(memoryQuery.value, { pageNo, pageSize })
        updateDatalist()
    }

    onMounted(() => {
        immediate && search()
    })

    return {
        page,
        dataList,
        loading,
        search,
        reset,
        query,
        onPageChange,
        data
    }
}
